package com.ruyuan.eshop.common.utils;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author zhonghuashishan
 */
public class DateUtil {

    /**
     * LocalDateTime 转换为 Date
     * @param date
     * @return
     */
    public static Date convertDate(LocalDateTime date) {
        if (date == null){
            return null;
        }
        return Date.from(date.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * Date 转换为 LocalDateTime
     * @param date
     * @return
     */
    public static LocalDateTime convertLocalDateTime(Date date) {
        if (date == null){
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * Date 转换为 LocalDate
     * @param date
     * @return
     */
    public static LocalDate convertLocalDate(Date date) {
        if (date == null){
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * Date 转换为 LocalTime
     * @param date
     * @return
     */
    public static LocalTime convertLocalTime(Date date) {
        if (date == null){
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
    }

    /**
     * 计算两个时间相差的分钟数
     *
     * @param start
     * @param end
     * @return
     */
    public static Long betweenMinutes(Date start, Date end) {
        return betweenMinutes(convertLocalDateTime(start), convertLocalDateTime(end));
    }

    /**
     * 计算两个时间相差的分钟数
     *
     * @param start
     * @param end
     * @return
     */
    public static Long betweenMinutes(LocalDateTime start, LocalDateTime end) {
        if (start == null || end == null) {
            return 0L;
        }
        Duration duration = Duration.between(start, end);
        return duration.toMinutes();
    }

}
